package cn.iocoder.yudao.module.scrm.controller.admin.product;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.collection.CollectionUtils;
import cn.iocoder.yudao.framework.common.util.number.NumberUtils;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
import cn.iocoder.yudao.framework.operatelog.core.annotations.OperateLog;
import cn.iocoder.yudao.module.scrm.controller.admin.product.vo.CrmProductPageReqVO;
import cn.iocoder.yudao.module.scrm.controller.admin.product.vo.CrmProductRespVO;
import cn.iocoder.yudao.module.scrm.controller.admin.product.vo.CrmProductSaveReqVO;
import cn.iocoder.yudao.module.scrm.dal.dataobject.product.CrmProductDO;
import cn.iocoder.yudao.module.scrm.enums.product.CrmProductStatusEnum;
import cn.iocoder.yudao.module.scrm.service.product.CrmProductService;
import cn.iocoder.yudao.module.system.api.dept.DeptApi;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertListByFlatMap;
import static cn.iocoder.yudao.framework.common.util.collection.MapUtils.findAndThen;
import static cn.iocoder.yudao.framework.operatelog.core.enums.OperateTypeEnum.EXPORT;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;

@Tag(name = "管理后台 - CRM 产品")
@RestController
@RequestMapping("/scrm/product")
@Validated
public class CrmProductController {

    @Resource
    private CrmProductService productService;

    @Resource
    private AdminUserApi adminUserApi;

    @Resource
    private DeptApi deptApi;



    @PostMapping("/create")
    @Operation(summary = "创建产品")
    @PreAuthorize("@ss.hasPermission('scrm:product:create')")
    public CommonResult<Long> createProduct(@Valid @RequestBody CrmProductSaveReqVO createReqVO) {
        createReqVO.setOwnerUserId(getLoginUserId());
        return success(productService.createProduct(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新产品")
    @PreAuthorize("@ss.hasPermission('scrm:product:update')")
    public CommonResult<Boolean> updateProduct(@Valid @RequestBody CrmProductSaveReqVO updateReqVO) {
        productService.updateProduct(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除产品")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('scrm:product:delete')")
    public CommonResult<Boolean> deleteProduct(@RequestParam("id") Long id) {
        productService.deleteProduct(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得产品")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('scrm:product:query')")
    public CommonResult<CrmProductRespVO> getProduct(@RequestParam("id") Long id) {
        CrmProductDO product = productService.getProduct(id);
        return success(buildProductDetail(product));
    }

    @GetMapping("/simple-list")
    @Operation(summary = "获得产品精简列表", description = "只包含被开启的产品，主要用于前端的下拉选项")
    public CommonResult<List<CrmProductRespVO>> getProductSimpleList() {
        List<CrmProductDO> list = productService.getProductListByStatus(CommonStatusEnum.ENABLE.getStatus());
        return success(CollectionUtils.convertList(list, product -> new CrmProductRespVO().setId(product.getId()).setName(product.getName())
                .setPrice(product.getPrice())));
    }

    @GetMapping("/page")
    @Operation(summary = "获得产品分页")
    @PreAuthorize("@ss.hasPermission('scrm:product:query')")
    public CommonResult<PageResult<CrmProductRespVO>> getProductPage(@Valid CrmProductPageReqVO pageVO) {
        PageResult<CrmProductDO> pageResult = productService.getProductPage(pageVO);
        return success(new PageResult<>(buildProductDetailList(pageResult.getList()), pageResult.getTotal()));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出产品 Excel")
    @PreAuthorize("@ss.hasPermission('scrm:product:export')")
    @OperateLog(type = EXPORT)
    public void exportProductExcel(@Valid CrmProductPageReqVO exportReqVO,
                                   HttpServletResponse response) throws IOException {
        exportReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<CrmProductDO> list = productService.getProductPage(exportReqVO).getList();
        //设置状体名称和创建人姓名
        List<CrmProductRespVO> bean = BeanUtils.toBean(list, CrmProductRespVO.class);
        bean.forEach(item->item.setStatusName(CrmProductStatusEnum.getNameByCode(item.getStatus()))
                .setCreatorName(adminUserApi.getUser(Long.valueOf(item.getCreator())).getCheckedData().getNickname()));
        // 导出 Excel
        ExcelUtils.write(response, "产品.xls", "数据", CrmProductRespVO.class,
                bean );
    }

    private CrmProductRespVO buildProductDetail(CrmProductDO crmProductDO) {
        if (crmProductDO == null) {
            return null;
        }
        return buildProductDetailList(Collections.singletonList(crmProductDO)).get(0);
    }

    private List<CrmProductRespVO> buildProductDetailList(List<CrmProductDO> crmProductDOList) {
        if (CollUtil.isEmpty(crmProductDOList)) {
            return Collections.emptyList();
        }
        // 1.1 获取创建人、负责人列表
        Map<Long, AdminUserRespDTO> userMap = adminUserApi.getUserMapNotCheckDataPermission(convertListByFlatMap(crmProductDOList,
                contact -> Stream.of(NumberUtils.parseLong(contact.getCreator()), contact.getOwnerUserId())));
        // 2. 拼接结果
        return BeanUtils.toBean(crmProductDOList, CrmProductRespVO.class, crmProductRespVO -> {
            // 2.2 拼接负责人、创建人名称
            findAndThen(userMap, crmProductRespVO.getOwnerUserId(), user -> {
                crmProductRespVO.setCreatorName(user.getNickname());
            });
        });
    }
}
